package com.canbot.u05.activity.roadGuide

import android.app.Activity
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.canbot.u05.R
import com.canbot.u05.activity.BaseActivityNoTitle
import com.canbot.u05.activity.inflate
import com.canbot.u05.activity.loadImage
import com.canbot.u05.activity.roadGuide.RoadSettingActivity.Companion.TYPE_ADD_BY_MAP
import com.canbot.u05.activity.roadGuide.RoadSettingActivity.Companion.TYPE_DELETE_BY_ID
import com.canbot.u05.activity.roadGuide.RoadSettingActivity.Companion.TYPE_GET_ALL
import com.canbot.u05.activity.roadGuide.RoadSettingActivity.Companion.TYPE_RENAME_BY_ID
import com.canbot.u05.activity.startActivityForResult
import com.canbot.u05.bean.guide.MapVoiceAndEyes
import com.canbot.u05.helper.DialogBuildHelper
import com.canbot.u05.helper.RoadRecyclerDecoration
import com.canbot.u05.socket.IpMsgConst
import com.canbot.u05.utils.OkHttpUtils
import com.canbot.u05.utils.PathConst
import com.canbot.u05.utils.ToastTools
import kotlinx.android.synthetic.main.road_guide_activity.*
import kotlinx.android.synthetic.main.road_item_pop.view.*
import kotlinx.android.synthetic.main.road_task_item.view.*
import java.util.*

/**
 * Created by zmp on 2019/7/5 13:37
 * @author zmp
 * 路径指引界面
 */
class RoadGuideActivity : BaseActivityNoTitle() {

    private lateinit var toastTools: ToastTools
    private var mAdapterPosition: Int = -1
    private var mMapID: Long = -1
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.road_guide_activity)
        toastTools = ToastTools.newInstance(this)
        //检查权限WindowManager 6.0权限检测
        if (!Settings.canDrawOverlays(this)) {
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName"))
            startActivityForResult(intent, REQ_CODE_OVERLAY)
            return
        }

        initView()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQ_CODE_OVERLAY) {
            if (Settings.canDrawOverlays(this)) {
                initView()
            } else {
                toastTools.showText(getString(R.string.permission_denied))
                finish()
            }
        }
        if (requestCode == REQ_CODE_ADD_OR_UPDATE && resultCode == Activity.RESULT_OK) {
            data?.getParcelableExtra<RoadGuideBean>(ROAD_GUIDE_INFO)?.let {
                if (mAdapterPosition == -1) {
                    mListOf.add(0, it)
                    roadGuideRecyclerView.adapter?.notifyItemInserted(0)
                    roadGuideRecyclerView.scrollToPosition(0)
                } else {
                    mListOf[mAdapterPosition] = it
                    roadGuideRecyclerView.adapter?.notifyItemChanged(mAdapterPosition)
                }
            }
        }
    }

    private val mListOf: MutableList<RoadGuideBean> by lazy {
        mutableListOf<RoadGuideBean>()
    }

    private fun initView() {
        enterGuideVoices[(Math.random() * enterGuideVoices.size).toInt()].playMapVoiceAndEyes()
        road_back_btn.setOnClickListener { finish() }
        roadAddIv.setOnClickListener {
            mAdapterPosition = -1
            startActivityForResult<RoadSettingActivity>(requestCode = REQ_CODE_ADD_OR_UPDATE)
        }
        roadGuideRecyclerView.layoutManager = LinearLayoutManager(this)
        roadGuideRecyclerView.adapter = MyAdapter()
        roadGuideRecyclerView.addItemDecoration(RoadRecyclerDecoration(this))
        initData()
    }

    private fun initData() {
        upDataType2Service(TYPE_GET_ALL)
    }

    private fun checkIsEmpty(): Boolean {
        if (mListOf.isEmpty() && mMapID != -1L) {
            showTipDialog(getString(R.string.road_guide_map_hint)) {
                upDataType2Service(TYPE_ADD_BY_MAP)
            }
            return true
        }
        return false
    }

    private val createDialogTip by lazy { DialogBuildHelper.createDialogTip(this) }
    private fun showTipDialog(content: String, block: () -> Unit) {
        createDialogTip.setContent(content, Gravity.CENTER)
                .setCancelable(false)
                .setClickListener(object : DialogBuildHelper.ITipClickListener() {
                    override fun sure() {
                        block()
                    }
                }, true).show()
    }

    private fun upDataType2Service(type: Int, position: Int? = null, newName: String? = null) {
        showBaseLoadDialog()
        val url = IpMsgConst.HTTP_URL_CHEST + "roadGuideAction"
        val hashMap = HashMap<String, Any>()
        hashMap["type"] = "$type"
        position?.let { hashMap["data"] = "${mListOf[it].id}" }
        newName?.let { hashMap["newName"] = it }

        OkHttpUtils.upLoadFile(url, hashMap, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String?) {
                Log.e(TAG, "upDataType2Service$result")
                dismissBaseDialog()
                when (type) {
                    TYPE_RENAME_BY_ID -> {
                        position?.let {
                            runOnUiThread {
                                mListOf[it].roadName = newName
                                roadGuideRecyclerView.adapter?.notifyItemChanged(it)
                            }
                        }
                    }
                    TYPE_DELETE_BY_ID -> {
                        runOnUiThread {
                            position?.let {
                                mListOf.removeAt(it)
                                roadGuideRecyclerView.adapter?.notifyItemRemoved(it)
                            }
                            checkIsEmpty()
                        }
                    }
                    TYPE_ADD_BY_MAP -> {
                        if (!result.isNullOrEmpty()) {
                            val mutableList = JSON.parseArray(result, RoadGuideBean::class.java)
                            if (!mutableList.isNullOrEmpty()) {
                                mListOf.addAll(mutableList.apply {
                                    this.reverse()
                                })
                                notifyMyAdapter()
                                return
                            }
                        }
                        showBaseHintDialog(getString(R.string.no_position_can_use))
                    }
                    TYPE_GET_ALL -> if (!result.isNullOrEmpty()) {
                        val roadGuideMsg = JSON.parseObject(result, RoadGuideMsg::class.java)
                        this@RoadGuideActivity.mMapID = roadGuideMsg.mapID
                        val roadGuides = roadGuideMsg.roadGuides
                        if (!roadGuides.isNullOrEmpty()) {
                            mListOf.addAll(roadGuides.apply {
                                this.reverse()
                            })
                            notifyMyAdapter()
                        } else {
                            runOnUiThread { checkIsEmpty() }
                        }
                    }
                }
            }

            override fun onFailure() {
                dismissBaseDialog()
                toastTools.showText(getString(R.string.service_error_hint))
                if (type == TYPE_GET_ALL) {
                    finish()
                }
            }
        })
    }

    fun notifyMyAdapter() {
        runOnUiThread {
            roadGuideRecyclerView.adapter?.notifyDataSetChanged()
        }
    }


    inner class MyAdapter : RecyclerView.Adapter<MyHolder>() {

        override fun onCreateViewHolder(p0: ViewGroup, p1: Int): MyHolder {
            return MyHolder(p0.inflate(R.layout.road_task_item))
        }

        override fun getItemCount(): Int {
            return mListOf.size
        }

        override fun onBindViewHolder(p0: MyHolder, p1: Int) {
            p0.bindData(mListOf[p1])
        }
    }

    inner class MyHolder(item: View) : RecyclerView.ViewHolder(item) {

        private lateinit var roadGuideBean: RoadGuideBean
        private val logoIv = item.logoIv
        private val roadNameTv = item.roadNameTv
        private val roadEditorIv: ImageView = item.roadEditorIv

        init {
            itemView.roadEditorIv.setOnClickListener {
                toastTools.showText("roadEditorIv$adapterPosition")
                showPopupWindow(roadGuideBean, roadEditorIv, adapterPosition)
            }
        }

        fun bindData(p1: RoadGuideBean) {
            roadGuideBean = p1
            roadNameTv.text = p1.roadName
            (p1.pointLogoPath ?: p1.pointGuidePath)?.let {
                logoIv.loadImage("${IpMsgConst.HTTP_URL_CHEST}${it.replaceFirst("/uupic/", "/uupic_thumb/")}", R.drawable.big_icon_a, R.drawable.big_icon_a)
            } ?: logoIv.setImageResource(R.drawable.big_icon_a)
        }
    }

    var popupWindow: PopupWindow? = null
    fun showPopupWindow(bean: RoadGuideBean, view: View, adapterPosition: Int) {
        if (popupWindow == null) {
            val inflate = View.inflate(this@RoadGuideActivity, R.layout.road_item_pop, null)
            popupWindow = PopupWindow(inflate, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT)
            popupWindow?.contentView?.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
            popupWindow?.isOutsideTouchable = true
            //设置 popupWindow外面可点击
            popupWindow?.setBackgroundDrawable(ColorDrawable())
        }
        popupWindow?.contentView?.let { contentView ->
            bindPopupView(contentView, bean, adapterPosition)
        }
        val location = IntArray(2)
        view.getLocationInWindow(location)
        Log.e("location", location[0].toString() + "," + location[1])
        val width = popupWindow?.contentView?.measuredWidth ?: 0
        popupWindow?.showAsDropDown(view, (-width * 0.7).toInt(), -resources.getDimension(R.dimen.px15).toInt())
    }

    private val reNameDialog by lazy { DialogBuildHelper.createDialogSetName(this@RoadGuideActivity) }

    private fun bindPopupView(contentView: View, bean: RoadGuideBean, adapterPosition: Int) {
        contentView.guide_pop_item_r2.setOnClickListener {
            popupWindow?.dismiss()
            this.mAdapterPosition = adapterPosition
            startActivityForResult<RoadSettingActivity>(requestCode = REQ_CODE_ADD_OR_UPDATE) {
                putExtra(ROAD_GUIDE_INFO, bean)
            }
        }

        contentView.guide_pop_item_r3.setOnClickListener {
            popupWindow?.dismiss()
            reNameDialog.setTitle(getString(R.string.task_renaming))
                    .setContent(bean.roadName)
                    .setClickListener(object : DialogBuildHelper.ISetNameClickListener() {
                        override fun sure(newName: String?, tipTextView: TextView?) {
                            if (newName.isNullOrEmpty()) {
                                tipTextView?.text = getString(R.string.task_cannot_empty)
                            } else {
                                reNameDialog.dismiss()
                                upDataType2Service(TYPE_RENAME_BY_ID, adapterPosition, newName)
                            }
                        }
                    }, false)
            reNameDialog.show()
        }
        contentView.guide_pop_item_r4.setOnClickListener {
            popupWindow?.dismiss()
            showTipDialog(getString(R.string.delete_task_hint)) {
                upDataType2Service(TYPE_DELETE_BY_ID, adapterPosition)
            }
        }
        contentView.taskNameTv.text = bean.roadName
        (bean.pointLogoPath ?: bean.pointGuidePath)?.let {
            contentView.taskLogoIv.loadImage(it.replaceFirst("/uupic/", "/uupic_thumb/"), R.drawable.big_icon_a, R.drawable.big_icon_a)
        } ?: contentView.taskLogoIv.setImageResource(R.drawable.big_icon_a)
    }


    private val enterGuideVoices = arrayOf(MapVoiceAndEyes.VoiceAndEyesInfo(ROAD_GUIDE_VOICE_DIR + "szdr_wlzy_u05_001.mp3", "34"),
            MapVoiceAndEyes.VoiceAndEyesInfo(ROAD_GUIDE_VOICE_DIR + "szdr_wlzy_u05_002.mp3", "12"))


    companion object {
        const val ROAD_GUIDE_VOICE_DIR = PathConst.BASE_AUDIO_PATH + "roadGuide/"
        const val TAG = "RoadGuideActivity"
        const val REQ_CODE_OVERLAY = 1000
        const val REQ_CODE_ADD_OR_UPDATE = 1001
        const val ROAD_GUIDE_INFO = "roadGuideInfo"
    }

}